package com.example.mybatisplus.controller;

import com.example.mybatisplus.des.User;
import com.example.mybatisplus.des.UserMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author longdeng
 * @Date 2020/9/17 0017 23:31
 */
@Component
public class UserService {

    @Autowired
    private UserMapper userMapper;

    private Logger logger = LoggerFactory.getLogger(UserService.class);

    private static Integer MAX_USER_NUM = 10000;
    /**
     * 每到100条数据就提交一次
     */
    private static Integer TJ_USER_NUM = 100;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Transactional
    public List<User> getUsers(Map<String, Object> map) {
        return userMapper.getUsers(map);
    }

    public List<User> addUsers() {
        List<User> userList = new ArrayList<>(TJ_USER_NUM);
        long start = System.currentTimeMillis();
        int index = 0;
        /*
        1.先生成批量的数据信息
         */
        for (int i = 0; i < MAX_USER_NUM; i++) {
            if (i == MAX_USER_NUM - 1) {
                userMapper.addUsers(userList);
                userList.clear();
                break;
            }
            index++;
            User user = new User();
            user.setUserid(UUID.randomUUID().toString().replace("-", ""));
            user.setName("zhouxl" + i);
            user.setAge(new Random().nextInt(100));
            userList.add(user);
            if (index == TJ_USER_NUM) {
                userMapper.addUsers(userList);
                userList.clear();
                index = 0;
            }
        }

        long end = System.currentTimeMillis();
        logger.info("{}耗时{}", "addUsers", (end - start));

        return null;
    }

    public List<User> addUserBySingle() {
        List<User> userList = new ArrayList<>();
        long start = System.currentTimeMillis();
        /*
        1.先生成批量的数据信息
         */
        for (int i = 0; i < MAX_USER_NUM; i++) {
            User user = new User();
            user.setUserid(UUID.randomUUID().toString().replace("-", ""));
            user.setName("zhouxl" + i);
            user.setAge(new Random().nextInt(100));
            userMapper.addUserBySingle(user);
            userList.add(user);
        }
        long end = System.currentTimeMillis();
        logger.info("{}耗时{}", "addUserBySingle", (end - start));
        return null;

    }

    public List<User> getUsersByCon(Map<String, Object> map) {
        return userMapper.getUsersByCon(map);
    }
}
